package com.bobo.rbac.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bobo.rbac.auth.utils.JwtUtils;
import com.bobo.rbac.auth.utils.ResponseResult;
import com.bobo.rbac.domain.Menu;
import com.bobo.rbac.domain.RoleMenu;
import com.bobo.rbac.service.MenuService;
import com.bobo.rbac.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: BOBO
 * @time: 2022/7/28 15:09
 */

@RestController
@RequestMapping("menu")
public class MenuController {
    @Autowired
    MenuService menuService;
    @Autowired
    RoleMenuService roleMenuService;

    /**
     * 保存或修改菜单
     *
     * @return
     */
    @RequestMapping("del")
    public ResponseResult del(Integer id) {
        menuService.removeById(id);
        return ResponseResult.ok();
    }



    /**
     * 保存或修改菜单
     *
     * @return
     */
    @RequestMapping("saveOrUpdate")
    public ResponseResult saveOrUpdate(@RequestBody  Menu menu) {
         menuService.saveOrUpdate(menu);
        return ResponseResult.ok();
    }


    /**
     * 获取菜单列表
     *
     * @return
     */
    @RequestMapping("getList")
    public ResponseResult getList() {
        List<Menu> list = menuService.list();
        return ResponseResult.ok(list);
    }


    /**
     * 根据登录者 获取树形菜单
     *
     * @return
     */
    @RequestMapping("getTreeMenuByUsername")
    public ResponseResult getTreeMenuByUsername() {
        String username = JwtUtils.getUsername();//从token获取登录的用户名
        List<Menu> list = menuService.getTreeMenuByUsername(username);
        return ResponseResult.ok(list);
    }


    /**
     * 获取所有树形菜单--比如管理员
     *
     * @return
     */
    @RequestMapping("getAllMenu")
    public ResponseResult getAllMenu() {
        String username = "admin";
        List<Menu> list = menuService.getTreeMenuByUsername(username);
        return ResponseResult.ok(list);
    }


    /**
     * 根据角色获取其拥有所有菜单id
     *
     * @return
     */
    @RequestMapping("getMidsByRid")
    public ResponseResult getAllMenu(Integer rid) {
        QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
        qw.eq("rid", rid);
        List<RoleMenu> list = roleMenuService.list(qw);
        List<Integer> mids = list.stream().map(rm -> rm.getMid()).collect(Collectors.toList());
        return ResponseResult.ok(mids);
    }


    /**
     * 测试树形
     * @param pid
     * @return
     */
    @RequestMapping("testTree")
    public ResponseResult testTree(@RequestParam(defaultValue = "0") Integer pid){
        List<Menu> menus = menuService.listByPid(pid);
        return ResponseResult.ok(menus);
    }
}
